import type { NoticeList } from './interface'
import { Swiper } from 'antd-mobile'
import { useLocalObservable } from 'mobx-react'
import { fetchNoticeList } from '../../api'
import { history } from 'umi'
import MessageImg from '@/static/notice/message.png'
import RightImg from '@/static/notice/right.png'
import styles from './index.module.less'
import classNames from 'classnames'
import React, { useEffect } from 'react'

interface Props {
    className?: string
    style?: React.CSSProperties
}

/** 通知 */
const NoticeSwiper: React.FC<Props> = props => {
    const store = useLocalObservable(() => ({
        /** 首页通知公告 */
        noticeList: [] as NoticeList.Data[],
        fetchNoticeListToStore: async () => {
            const data = await fetchNoticeList()
            store.noticeList = data
        },
    }))

    useEffect(() => {
        store.fetchNoticeListToStore()
    }, [store])

    const onNavToNoticeDetail = (item: NoticeList.Data) => {
        history.push({
            pathname: '/notice/detail',
            query: {
                id: String(item.id),
            },
        })
    }

    return (
        <div className={classNames(styles.notice, props.className)} style={props.style}>
            <Swiper
                autoplay
                direction={'vertical'}
                autoplayInterval={1000 * 3}
                loop
                indicator={() => <></>}
                allowTouchMove={false}
                style={{ '--height': '95px' }}
            >
                {store.noticeList?.length ? (
                    store.noticeList.map(item => (
                        <Swiper.Item
                            key={item.id}
                            onClick={() => {
                                onNavToNoticeDetail(item)
                            }}
                        >
                            <div className={styles.notice_item}>
                                <img src={MessageImg} />
                                <div> {item.title}</div>
                                <img src={RightImg} />
                            </div>
                        </Swiper.Item>
                    ))
                ) : (
                    <Swiper.Item>
                        <div className={styles.notice_item}>
                            <img src={MessageImg} />
                            <div> 暂无公告</div>
                            <img src={RightImg} />
                        </div>
                    </Swiper.Item>
                )}
            </Swiper>
        </div>
    )
}

export default NoticeSwiper
